package com.example.studentknowledgesys.controller;

import com.example.studentknowledgesys.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 光的代言人
 */
@RestController
@RequestMapping("/api/upload")
public class ImageController {
    @Value("${uploadPath}")
    private String uploadPath;

    @PostMapping("/img")
    public Result uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error(400, "上传失败，请选择文件");
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;
        try {
            File file1 = new File(uploadPath + newFileName);
            file.transferTo(file1);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return Result.error(500, "上传失败，请稍后重试！");
        }
        return new Result(200, "图片上传成功！", newFileName);
    }

    @PostMapping("/editorImage")
    public Map<String, Object> uploadFile(@RequestParam("editorImage") MultipartFile file) throws IOException {
        String  fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;
        File file1 = new File(uploadPath + newFileName);
        file.transferTo(file1);
        Map<String, Object> map=new HashMap<>();
        map.put("errno",0);
        Map<String, Object> data=new HashMap<>();
        data.put("url","http://localhost:8082/upload/"+newFileName);
        data.put("alt","无法加载图片");
        map.put("data",data);
        return map;

    }

}
